package com.yohann.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yohann.eduservice.entity.EduSubject;
import com.yohann.eduservice.entity.excel.SubjectData;
import com.yohann.eduservice.entity.vo.OneSubject;
import com.yohann.eduservice.entity.vo.TwoSubject;
import com.yohann.eduservice.listener.SubjectExcelListener;
import com.yohann.eduservice.mapper.EduSubjectMapper;
import com.yohann.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Yohann
 * @since 2020-08-07
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Autowired
    private SubjectExcelListener subjectExcelListener;

    /**
     * 添加课程分类
     * @param file
     * @param subjectService
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,subjectExcelListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有科目
     * @return
     */
    @Override
    public List<OneSubject> getAllOneSubject() {
        //查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjects = this.list(wrapperOne);

        //查询所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjects = this.list(wrapperTwo);

        List<OneSubject> finalSubjects = new ArrayList<>();

        //封装一级分类
        for (EduSubject oneSubject : oneSubjects) {
            ArrayList<TwoSubject> twoSubjectArrayList = new ArrayList<>();

            //封装二级分类
            for (EduSubject twoSubject : twoSubjects) {

                if (twoSubject.getParentId().equals(oneSubject.getId())){
                    twoSubjectArrayList.add(new TwoSubject(twoSubject.getId(),twoSubject.getTitle()));
                }
            }

            finalSubjects.add(new OneSubject(oneSubject.getId(),oneSubject.getTitle(),twoSubjectArrayList));
        }

        return finalSubjects;
    }
}
